using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FiltronASP.Models.DAO.Filtron;
using FiltronASP.Models.DAO.Interfaces.Filtron;
using FiltronASP.Models;
using FiltronASP.Helpers.Translations;
using FiltronASP.Helpers.CatalogueHelpers;
using FiltronASP.Logger;
using System.Text;

namespace FiltronASP.Helpers.AjaxModel
{
    public static class FiltersTableHelper
    {

        public static string generateFiltersTable(int engineId, int modelId, string languageName, int vehicleId) {
            
            if ((engineId.Equals(0)) || (modelId.Equals(0))) {
                return "nulls";
            }

            int airCol = 6;
            if (languageName == "polish")
            {
                airCol = 7;
            }
            StringBuilder sbLeft = new StringBuilder();
            StringBuilder sbRight = new StringBuilder();
            sbLeft.Append("<div class='col-lg-6 col-md-12 col-sm-12  col-xs-12 no-padding mar-top-20'>");
            sbLeft.Append(generateTableHeaderLeftPart(languageName));

            sbRight.Append("<div class='col-lg-6 col-md-12 col-sm-12  col-xs-12 no-padding mar-top-20'>");
            sbRight.Append(generateTableHeaderRightPart(languageName));

            bool showStyleInfo = false;
            bool isHdTruck = testIsHd(modelId);
            IFiltronFilterEngineDAO filtronFilterEngine = new FiltronFilterEngineDAO();
            IFiltronEngineDAO filtronEngineDAO = new FiltronEngineDAO();
            IFiltronFilterDAO filtronFilterDAO = new FiltronFilterDAO();
            IFiltronFilterEngineCommentsDAO filtronFilterEngineCommentsDAO = new FiltronFilterEngineCommentsDAO();
            string toReturn = String.Empty;
            string engineName = String.Empty;
            // wyciągam rok produkcji silnika
            FiltronEngine singleEngine = filtronEngineDAO.FindByPK(engineId);
            if (singleEngine != null)
            {
                engineName = singleEngine.engine_name;
            }

            List<string> filtersWithDateAndDescTrs = new List<string>();
            List<FilterRow> filterRows = new List<FilterRow>();
            IQueryable<FiltronFilterEngine> filtronFilterEngineWithDateDescCollectionInner =
            filtronFilterEngine.FindByEngineAndModel(engineId, modelId);
            if (filtronFilterEngineWithDateDescCollectionInner != null)
            {
                foreach (FiltronFilterEngine singleFiltronFilterEngineDateDescInner in filtronFilterEngineWithDateDescCollectionInner)
                {
                    IQueryable<FiltronFilterEngineComment> FilterEngineCommentsSpecifiedDescription =
                    filtronFilterEngineCommentsDAO.FindByFilterEngineIdDescAndYear(singleFiltronFilterEngineDateDescInner.filter_engine_id);
                    if (FilterEngineCommentsSpecifiedDescription != null)
                    {
                        foreach (FiltronFilterEngineComment singleSpecifiedDesc in FilterEngineCommentsSpecifiedDescription)
                        {
                            FiltronFilter singleFilter = filtronFilterDAO.FindByPK(singleFiltronFilterEngineDateDescInner.filter_id);
                            if (!filterRows.Any())
                            {
                                filterRows.Add(FiltersTableHelper.GetNewFilterRow(singleFilter, singleSpecifiedDesc, isHdTruck));
                            }
                            else
                            {
                                filterRows = FiltersTableHelper.UpdateFilterRows(singleFilter, singleSpecifiedDesc, filterRows, isHdTruck);
                            }
                        }
                    }
                }
            }

            // filtry bez daty i bez opisu

            List<int> filtersWithNulls = new List<int>();
            List<string> filtersWithNullsTrs = new List<string>();
            IQueryable<FiltronFilterEngine> filtronFilterEngineNulls = 
                filtronFilterEngine.FindByEngineAndModelOnlyNulls(engineId, modelId);
            if (filtronFilterEngineNulls != null) {
                foreach (FiltronFilterEngine singleNull in filtronFilterEngineNulls) {
                    if (!(filtersWithNulls.Contains(singleNull.filter_id))) {
                        filtersWithNulls.Add(singleNull.filter_id);
                    }
                }
            }
            if (filtersWithNulls.Count > 0) {
                for (int nullInterval = 0; nullInterval < filtersWithNulls.Count; nullInterval++)
                {
                    FiltronFilter singleFilter = filtronFilterDAO.FindByPK(filtersWithNulls[nullInterval]);
                    FiltronFilterEngineComment comment = new FiltronFilterEngineComment();
                    comment.filter_info_description = String.Empty;
                    comment.filter_info_years = String.Empty;
                    if (!filterRows.Any())
                    {
                        filterRows.Add(FiltersTableHelper.GetNewFilterRow(singleFilter, comment, isHdTruck));
                    }
                    else
                    {
                        filterRows = FiltersTableHelper.UpdateFilterRows(singleFilter, comment, filterRows, isHdTruck);
                    }
                }
            }
            filterRows = FiltersTableHelper.ReorderFilterRows(filterRows);
            string prevYears = String.Empty;
            foreach (FilterRow filterRow in filterRows)
            {
                string filtersWithSpecifiedYearInterval = String.Empty;
                if (filterRow.Years.Equals(prevYears))
                {
                    sbLeft.Append(FiltersTableHelper.generateFilterLeftPart(filterRow, false, isHdTruck, airCol));
                    sbRight.Append(FiltersTableHelper.generateFilterRightPart(filterRow, isHdTruck));
                }   //if
                else
                {
                    sbLeft.Append(FiltersTableHelper.generateFilterLeftPart(filterRow, true, isHdTruck, airCol));
                    sbRight.Append(FiltersTableHelper.generateFilterRightPart(filterRow, isHdTruck));
                }   //else
                prevYears = filterRow.Years;
                if (!showStyleInfo)
                {
                    if (filterRow.ShowStyleInfo)
                    {
                        showStyleInfo = filterRow.ShowStyleInfo;
                    }
                }
            }
            //tablice
            sbLeft.Append("</div>");
            sbRight.Append("</div>");
            StringBuilder sb = new StringBuilder();
            sb.Append(sbLeft.ToString());
            sb.Append(sbRight.ToString());
            if (showStyleInfo)
            {
                sb.Append(addStyleInfo(languageName));
            }
            return sb.ToString();
        }

        private static bool testIsHd(int modelId)
        {
            IFiltronMakeDAO filtronMakeDAO = new FiltronMakeDAO();
            IQueryable<FiltronMake> makes = filtronMakeDAO.FindByModel(modelId);
            if (makes != null)
            {
                foreach (FiltronMake m in makes)
                    if (m.vehicle_id == 3)
                        return true;
            }
            return false;
        }

        private static string addStyleInfo(string languageName)
        {
            string toReturn = "<div class=\"filterStyleInfo\" style='font-size: 12px; margin-top: 10px; text-align: center;'>";
            toReturn += "<b>AD</b> = " + translationHelper.getTranslation("_filterStyleInfoAD", languageName) + ", ";
            toReturn += "<b>AS</b> = " + translationHelper.getTranslation("_filterStyleInfoAS", languageName) + ", ";
            toReturn += "<b>H</b> = " + translationHelper.getTranslation("_filterStyleInfoH", languageName) + ", ";
            toReturn += "<b>T</b> = " + translationHelper.getTranslation("_filterStyleInfoT", languageName) + ", ";
            toReturn += "<b>W</b> = " + translationHelper.getTranslation("_filterStyleInfoW", languageName);
            toReturn += "</div>";
            return toReturn;
        }

        private static string getFilterStyleFromFilter(FiltronFilter singleFilter)
        {
            FiltronFilterStyleDAO filterStyleDAO = new FiltronFilterStyleDAO();
            string toReturn = "";
            if (singleFilter.filter_style_id != null)
                toReturn = " (" + filterStyleDAO.FindByPK(singleFilter.filter_style_id).style_abbr + ")";

            return toReturn;
        }

        private static string generateTableHeaderLeftPart(string languageName)
        {
            int airCol = 6;
            int airCol2 = 6;
            if (languageName == "polish")
            {
                airCol = 7;
                airCol2 = 5;
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("<div class='col-xs-12 no-padding'>");
            sb.Append("<div class='col-sm-6 col-xs-6 no-padding overlay-engine2 '>");
            sb.Append("<div class='col-xs-5 no-padding '>");
            sb.Append(String.Format("<img class='img-responsive sand-clock' src='{0}' alt='cc'>", VirtualPathUtility.ToAbsolute("~/Content/img/sand-clock.png")));
            sb.Append("</div>");
            sb.Append("<div class='col-xs-7 no-padding overlay-engine-boder-r overlay-engine-boder-l'>");
            sb.Append(String.Format("<p>{0}</p>", translationHelper.getTranslation("_hlpDescription", languageName)));
            sb.Append("</div>");
            sb.Append("</div>");
            sb.Append("<div class='col-sm-6 col-xs-6 no-padding no-padding overlay-engine2'>");
            sb.Append(String.Format("<div class='col-xs-{0} no-padding overlay-engine-boder-r'>", airCol.ToString()));
            sb.Append(String.Format("<p>{0}</p>", translationHelper.getTranslation("_airFilter", languageName)));
            sb.Append(String.Format("<img class='img-responsive' src='{0}' alt='cc'>", VirtualPathUtility.ToAbsolute("~/Content/img/car-fan.png")));
            sb.Append("</div>");
            sb.Append(String.Format("<div class='col-xs-{0} no-padding overlay-engine-boder-r'>", airCol2.ToString()));
            sb.Append(String.Format("<p>{0}</p>", translationHelper.getTranslation("_oilFilter", languageName)));
            sb.Append(String.Format("<img class='img-responsive' src='{0}' alt='cc' style='margin-top: 5px;'>", VirtualPathUtility.ToAbsolute("~/Content/img/oil-drop.png")));
            sb.Append("</div>");
            sb.Append("</div>");
            sb.Append("</div>");
            return sb.ToString();
        }

        private static string generateTableHeaderRightPart(string languageName)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<div class='col-xs-12 no-padding'>");
            sb.Append("<div class='col-sm-3 col-xs-3 no-padding overlay-engine2 overlay-engine-boder-r'>");
            sb.Append("<p>Fuel</p>");
            sb.Append(String.Format("<img class='img-responsive' src='{0}' alt='cc'>", VirtualPathUtility.ToAbsolute("~/Content/img/tank-ikon.png")));
            sb.Append("</div>");
            sb.Append("<div class='col-sm-6 col-xs-6 no-padding overlay-engine2 overlay-engine-boder-r'>");
            sb.Append(String.Format("<p class='cabin'>{0}</p>", translationHelper.getTranslation("_cabinFilter", languageName)));
            sb.Append("<div class='col-xs-6  no-padding'>");
            sb.Append(String.Format("<p class='cabin-paper'>{0}</p>", translationHelper.getTranslation("_cabinPaper", languageName)));
            sb.Append("</div>");
            sb.Append("<div class='col-xs-6  no-padding'>");
            sb.Append(String.Format("<p class='cabin-carbon'>{0}</p>", translationHelper.getTranslation("_cabinCarbon", languageName)));
            sb.Append("</div>");
            sb.Append("</div>");
            sb.Append("<div class='col-sm-3 col-xs-3 no-padding overlay-engine2 '>");
            sb.Append(String.Format("<p>{0}</p>", translationHelper.getTranslation("_hlpOther", languageName)));
            sb.Append("<p>Other</p>");
            sb.Append("</div>");
            sb.Append("</div>");
            return sb.ToString();
        }

        private static string generateFilterLeftPart(FilterRow filterRow, bool withYears, bool isHdTruck)
        {
            return FiltersTableHelper.generateFilterLeftPart(filterRow, withYears, isHdTruck, 6);
        }
        private static string generateFilterLeftPart(FilterRow filterRow, bool withYears, bool isHdTruck, int airCol)
        {
            if (filterRow == null)
            {
                return String.Empty;
            }   //if
            int airCol2 = 12 - airCol;
            StringBuilder sb = new StringBuilder();
            sb.Append("<div class='col-xs-12 no-padding filter-border-l-r'>");
            sb.Append("<div class='col-sm-6 col-xs-6 no-padding filter-nfo filter-nfo-center-parent '>");
            sb.Append("<div class='col-xs-5 no-padding filter-nfo-center-parent filter-border-r'>");
            if (withYears)
            {
                sb.Append(String.Format("<p class='filter-nfo-light  filter-nfo-center-child'>{0}</p>", filterRow.Years));
            }   //if
            else
            {
                sb.Append(String.Format("<p class='filter-nfo-light  filter-nfo-center-child'>{0}</p>", String.Empty));
            }   //else
            sb.Append("</div>");
            sb.Append("<div class='col-xs-7 no-padding filter-nfo-center-parent filter-border-r '>");
            sb.Append(String.Format("<p  class='filter-nfo-light filter-nfo-center-child' style='top:25%;'>{0}</p>", filterRow.Desc));
            sb.Append("</div>");
            sb.Append("</div>");
            sb.Append("<div class='col-sm-6 col-xs-6 no-padding no-padding filter-nfo '>");
            sb.Append(String.Format("<div class='col-xs-{0} no-padding filter-nfo-center-parent filter-border-r filter-hover'>", airCol.ToString()));
            sb.Append(String.Format("<p  class='filter-nfo-bold filter-nfo-center-child'><span style='cursor: pointer' class='filter-selector' data-filter='{0}' data-is-hd-truck='{2}'>{1}</span></p>", filterRow.AirId, filterRow.AirDesc, isHdTruck));
            sb.Append("</div>");
            sb.Append(String.Format("<div class='col-xs-{0} no-padding filter-nfo-center-parent filter-hover'>", airCol2.ToString()));
            sb.Append(String.Format("<p  class='filter-nfo-bold filter-nfo-center-child'><span style='cursor: pointer' class='filter-selector' data-filter='{0}' data-is-hd-truck='{2}'>{1}</span></p>", filterRow.OilId, filterRow.OilDesc, isHdTruck));
            sb.Append("</div>");
            sb.Append("</div>");
            sb.Append("</div>");
            return sb.ToString();
        }

        private static string generateFilterRightPart(FilterRow filterRow, bool isHdTruck)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<div class='col-xs-12 no-padding  filter-border-l-r'>");
            sb.Append("<div class='col-sm-3 col-xs-3 no-padding filter-nfo-center-parent filter-border-r filter-hover'>");
            sb.Append(String.Format("<p  class='filter-nfo-bold filter-nfo-center-child'><span style='cursor: pointer' class='filter-selector' data-filter='{0}' data-is-hd-truck='{2}'>{1}</span></p>", filterRow.FuelId, filterRow.FuelDesc, isHdTruck));
            sb.Append("</div>");
            sb.Append("<div class='col-sm-6 col-xs-6 no-padding  filter-border-r'>");
            sb.Append("<div class='col-xs-6 filter-nfo-center-parent no-padding filter-hover'>");
            sb.Append(String.Format("<p  class='filter-nfo-bold filter-nfo-center-child'><span style='cursor: pointer' class='filter-selector' data-filter='{0}' data-is-hd-truck='{2}'>{1}</span></p>", filterRow.PaperId, filterRow.PaperDesc, isHdTruck));
            sb.Append("</div>");
            sb.Append("<div class='col-xs-6 filter-nfo-center-parent no-padding filter-hover'>");
            sb.Append(String.Format("<p  class='filter-nfo-bold filter-nfo-center-child'><span style='cursor: pointer' class='filter-selector' data-filter='{0}' data-is-hd-truck='{2}'>{1}</span></p>", filterRow.CarbonId, filterRow.CarbonDesc, isHdTruck));
            sb.Append("</div>");
            sb.Append("</div>");
            sb.Append("<div class='col-sm-3 col-xs-3 no-padding filter-nfo-center-parent filter-hover'>");
            sb.Append(String.Format("<p  class='filter-nfo-bold filter-nfo-center-child'><span style='cursor: pointer' class='filter-selector' data-filter='{0}' data-is-hd-truck='{2}'>{1}</span></p>", filterRow.OtherId, filterRow.OtherDesc, isHdTruck));
            sb.Append("</div>");
            sb.Append("</div>");
            return sb.ToString();
        }

        private static FilterRow GetNewFilterRow(FiltronFilter filter, FiltronFilterEngineComment comment, bool isHdTruck)
        {
            if ((filter == null) || (comment == null))
            {
                return null;
            }   //if
            try
            {
                if (filter.filter_style_id.Equals(1))
                {
                    FilterRow newFilterRow = new FilterRow();
                    newFilterRow.Years = comment.filter_info_years;
                    newFilterRow.Desc = comment.filter_info_description;
                    newFilterRow.OilDesc = FiltronHelper.GetFiltronFilterNumber(filter, isHdTruck);
                    newFilterRow.OilId = filter.filter_id;
                    return newFilterRow;
                }
                if (filter.filter_style_id.Equals(2))
                {
                    FilterRow newFilterRow = new FilterRow();
                    newFilterRow.Years = comment.filter_info_years;
                    newFilterRow.Desc = comment.filter_info_description;
                    newFilterRow.AirDesc = FiltronHelper.GetFiltronFilterNumber(filter, isHdTruck);
                    newFilterRow.AirId = filter.filter_id;
                    return newFilterRow;
                }
                if (filter.filter_style_id.Equals(3))
                {
                    FilterRow newFilterRow = new FilterRow();
                    newFilterRow.Years = comment.filter_info_years;
                    newFilterRow.Desc = comment.filter_info_description;
                    newFilterRow.FuelDesc = FiltronHelper.GetFiltronFilterNumber(filter, isHdTruck);
                    newFilterRow.FuelId = filter.filter_id;
                    return newFilterRow;
                }
                if (filter.filter_style_id.Equals(4))
                {
                    string wixNumberDate = FiltronHelper.GetFiltronFilterNumber(filter, isHdTruck);
                    if (FiltronASP.Helpers.StringExtensions.StringExtension.ifLastDigitIsOdd(wixNumberDate))
                    {
                        FilterRow newFilterRow = new FilterRow();
                        newFilterRow.Years = comment.filter_info_years;
                        newFilterRow.Desc = comment.filter_info_description;
                        newFilterRow.PaperDesc = FiltronHelper.GetFiltronFilterNumber(filter, isHdTruck);
                        newFilterRow.PaperId = filter.filter_id;
                        return newFilterRow;
                    } 
                    else
                    {
                        FilterRow newFilterRow = new FilterRow();
                        newFilterRow.Years = comment.filter_info_years;
                        newFilterRow.Desc = comment.filter_info_description;
                        newFilterRow.CarbonDesc = FiltronHelper.GetFiltronFilterNumber(filter, isHdTruck);
                        newFilterRow.CarbonId = filter.filter_id;
                        return newFilterRow;
                    }   //else
                }
                if ((filter.filter_style_id.Equals(5)) || (filter.filter_style_id.Equals(6)) ||
                                            (filter.filter_style_id.Equals(7)) || (filter.filter_style_id.Equals(8)) ||
                                            (filter.filter_style_id.Equals(9)) || (filter.filter_style_id.Equals(10)))
                {
                    string styleInfo = getFilterStyleFromFilter(filter);
                    FilterRow newFilterRow = new FilterRow();
                    newFilterRow.Years = comment.filter_info_years;
                    newFilterRow.Desc = comment.filter_info_description;
                    newFilterRow.OtherDesc = FiltronHelper.GetFiltronFilterNumber(filter, isHdTruck) + styleInfo;
                    newFilterRow.OtherId = filter.filter_id;
                    if (styleInfo != "")
                    {
                        newFilterRow.ShowStyleInfo = true;
                    }
                    return newFilterRow;
                }
            }   //try
            catch (Exception ex)
            {
                MyLogger.Log(ex);
            }   //catch
            return null;
        }

        private static List<FilterRow> UpdateFilterRows(FiltronFilter filter, FiltronFilterEngineComment comment, List<FilterRow> filterRows, bool isHdTruck) 
        {
            if ((filter == null) || (comment == null))
            {
                return filterRows;
            }   //if
            try
            {
                foreach (FilterRow filterRow in filterRows)
                {
                    if ((filterRow.Years.Equals(comment.filter_info_years)) && (filterRow.Desc.Equals(comment.filter_info_description)))
                    {
                        if (filter.filter_style_id.Equals(1))
                        {
                            if (String.IsNullOrEmpty(filterRow.OilDesc))
                            {
                                filterRow.OilDesc = FiltronHelper.GetFiltronFilterNumber(filter, isHdTruck);
                                filterRow.OilId = filter.filter_id;
                                return filterRows;
                            }   //if
                        }
                        if (filter.filter_style_id.Equals(2))
                        {
                            if (String.IsNullOrEmpty(filterRow.AirDesc))
                            {
                                filterRow.AirDesc = FiltronHelper.GetFiltronFilterNumber(filter, isHdTruck);
                                filterRow.AirId = filter.filter_id;
                                return filterRows;
                            }   //if
                        }
                        if (filter.filter_style_id.Equals(3))
                        {
                            if (String.IsNullOrEmpty(filterRow.FuelDesc))
                            {
                                filterRow.FuelDesc = FiltronHelper.GetFiltronFilterNumber(filter, isHdTruck);
                                filterRow.FuelId = filter.filter_id;
                                return filterRows;
                            }   //if
                        }
                        if (filter.filter_style_id.Equals(4))
                        {
                            string wixNumberDate = FiltronHelper.GetFiltronFilterNumber(filter);
                            if (FiltronASP.Helpers.StringExtensions.StringExtension.ifLastDigitIsOdd(wixNumberDate))
                            {
                                if (String.IsNullOrEmpty(filterRow.PaperDesc))
                                {
                                    filterRow.PaperDesc = FiltronHelper.GetFiltronFilterNumber(filter, isHdTruck);
                                    filterRow.PaperId = filter.filter_id;
                                    return filterRows;
                                }   //if
                            }
                            else
                            {
                                if (String.IsNullOrEmpty(filterRow.CarbonDesc))
                                {
                                    filterRow.CarbonDesc = FiltronHelper.GetFiltronFilterNumber(filter, isHdTruck);
                                    filterRow.CarbonId = filter.filter_id;
                                    return filterRows;
                                }   //if
                            }
                        }
                        if ((filter.filter_style_id.Equals(5)) || (filter.filter_style_id.Equals(6)) ||
                            (filter.filter_style_id.Equals(7)) || (filter.filter_style_id.Equals(8)) ||
                            (filter.filter_style_id.Equals(9)) || (filter.filter_style_id.Equals(10)))
                        {
                            string styleInfo = getFilterStyleFromFilter(filter);
                            if (String.IsNullOrEmpty(filterRow.OtherDesc))
                            {
                                filterRow.OtherDesc = FiltronHelper.GetFiltronFilterNumber(filter, isHdTruck) + styleInfo;
                                filterRow.OtherId = filter.filter_id;
                                if (styleInfo != "")
                                {
                                    filterRow.ShowStyleInfo = true;
                                }
                                return filterRows;
                            }   //if
                        }
                    }   //if
                }   //for
                FilterRow newFilterRow = FiltersTableHelper.GetNewFilterRow(filter, comment, isHdTruck);
                filterRows.Add(newFilterRow);
            }   //catch
            catch (Exception ex)
            {
                MyLogger.Log(ex);
            }   //catch
            return filterRows;
        }

        private static List<FilterRow> ReorderFilterRows(List<FilterRow> filterRows)
        {
            if (filterRows == null)
            {
                return filterRows;
            }   //if
            if (!filterRows.Any())
            {
                return filterRows;
            }   //if
            return filterRows.OrderBy(x => x.YearTo).ThenBy(x => x.MonthTo).ThenBy(x => x.Desc).ToList();
        }

    }
}